//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.salesperson;

import java.awt.event.*;
import java.beans.PropertyVetoException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import org.jpgolay.gui.date.DateComboBox;
import org.jpgolay.gui.fixed.*;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.me.discount.PopupDiscountGUI;
import org.jpgolay.me.family.Family;
import org.jpgolay.me.item.ItemCRUD;
import org.jpgolay.me.persistence.ObjectCRUD;
import org.jpgolay.me.persistence.SQLList;
import org.jpgolay.me.salesperson.commission.Commission;
import org.jpgolay.me.util.*;

// Referenced classes of package org.jpgolay.me.salesperson:
//            SalesPersonGUI, SalesPerson, SalesPersonPrint
public class SalesPersonController extends SalesPersonGUI {

    private class MouseClickItemCommissionList extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            if (e.getButton() != 1 && getItemCommissionTable().isCellEditable()) {
                getPopupDiscount().show(e.getComponent(), e.getX(), e.getY());
            }
        }

        MouseClickItemCommissionList() {
        }
    }

    private class MouseClickFamilyCommissionList extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            if (e.getButton() != 1 && getFamilyCommissionTable().isCellEditable()) {
                getPopupDiscount().show(e.getComponent(), e.getX(), e.getY());
            }
        }

        MouseClickFamilyCommissionList() {
        }
    }

    private class MouseClickItemList extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2 && getItemCommissionTable().isCellEditable()) {
                getItemCommissionTable().getTable().setValueAt(itemTable.getTable().getValueAt(itemTable.getTable().getSelectedRow(), 0), getItemCommissionTable().getTable().getSelectedRow(), 0);
            }
        }

        MouseClickItemList() {
        }
    }

    public SalesPersonController(Parameter param) {
        create = false;
        updateRowsTable = true;
        write = false;
        popupDiscount = null;
        itemTable = null;
        calendarPeriod = null;
        this.param = param;
        crud = new ObjectCRUD();
        itemCrud = new ItemCRUD();
        initLaw();
        initMenu();
        initIconBar();
        initField();
        initSalesPersonList();
        initSalesPersonFamilyList();
        initItemCommission();
        initFamilyCommission();
        initPopupDiscountListener();
        initItemSearch();
        initItemListTable();
        initCalendar();
    }

    private void initLaw() {
        if (param.getAccessLaw().length() >= 23 && param.getAccessLaw().charAt(23) == '1') {
            write = true;
        }
    }

    private void initMenu() {
        getMenuPanel().getExit().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionExit();
            }
        });
        getMenuPanel().getDelete().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionRemove();
            }
        });
        getMenuPanel().getHelp().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionHelp();
            }
        });
        getMenuPanel().getModify().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionModify();
            }
        });
        getMenuPanel().getNew().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionNew();
            }
        });
        getMenuPanel().getOpen().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionevent) {
            }
        });
        getMenuPanel().getPrint().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionPrint(true);
            }
        });
        getMenuPanel().getSave().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSave();
            }
        });
    }

    private void initIconBar() {
        getIconBarPanel().addAnswerListener(new AnswerListener() {
            public void create(AnswerEvent e) {
                actionNew();
            }

            public void open(AnswerEvent answerevent) {
            }

            public void modify(AnswerEvent e) {
                actionModify();
            }

            public void save(AnswerEvent e) {
                actionSave();
            }

            public void remove(AnswerEvent e) {
                actionRemove();
            }

            public void print(AnswerEvent e) {
                actionPrint(false);
            }

            public void help(AnswerEvent e) {
                actionHelp();
            }
        });
    }

    private void initField() {
        cleanField();
        setEnabledField(false);
        getIconBarPanel().setEnabledCreate(write);
        getIconBarPanel().setEnabledSave(false);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(false);
        getIconBarPanel().setEnabledPrint(false);
        getIconBarPanel().setEnabledOpen(false);
        getMenuPanel().getNew().setEnabled(write);
        getMenuPanel().getSave().setEnabled(false);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(false);
        getMenuPanel().getPrint().setEnabled(false);
        getMenuPanel().getOpen().setEnabled(false);
        create = false;
        itemCommissionList = null;
        familyCommissionList = null;
    }

    private void initSalesPersonList() {
        java.util.Collection c = crud.readAll(null, 15);
        if (c != null) {
            SalesPerson salesPerson = null;
            salesPersonList = new ArrayList(c);
            Iterator it = salesPersonList.iterator();
            String list[] = new String[salesPersonList.size()];
            for (int i = 0; it.hasNext(); i++) {
                salesPerson = (SalesPerson) it.next();
                list[i] = salesPerson.getPrenom() + " " + salesPerson.getNom();
            }

            setSalesPersonList(list);
            getSalesPersonComboBox().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionLoad(getSalesPersonComboBox().getSelectedIndex());
                }
            });
        } else {
            setSalesPersonList(new String[]{
                        "aucun"
                    });
        }
    }

    private void initSalesPersonFamilyList() {
        java.util.Collection c = crud.readAll(null, 39);
        if (c != null) {
            Family family = null;
            ArrayList familyList = new ArrayList(c);
            Iterator it = familyList.iterator();
            String list[] = new String[familyList.size()];
            for (int i = 0; it.hasNext(); i++) {
                family = (Family) it.next();
                list[i] = family.getId();
            }

            setFamilyList(list);
        } else {
            setFamilyList(new String[]{
                        "aucune"
                    });
        }
    }

    private void initItemCommission() {
        getItemCommissionTable().setTypes(new Class[]{
                    java.lang.String.class, java.math.BigDecimal.class, java.lang.String.class, java.lang.String.class
                });
        getItemCommissionTable().setLastColumnNotEditable(-1);
        getItemCommissionTable().setCellEditable(false);
        getItemCommissionTable().setAlternateColor(MEUtility.ITEM_COMMISSION_LINE);
        getItemCommissionTable().setColumnNames(new String[]{
                    "ARTICLE", "TAUX", "DEBUT", "FIN"
                });
        getItemCommissionTable().setPreferredColumnSize(new int[]{
                    80, 70, 75, 75
                });
        getItemCommissionTable().setData(getCommissionEmptyTable());
    }

    private void initFamilyCommission() {
        getFamilyCommissionTable().setTypes(new Class[]{
                    java.lang.String.class, java.math.BigDecimal.class, java.lang.String.class, java.lang.String.class
                });
        getFamilyCommissionTable().setLastColumnNotEditable(-1);
        getFamilyCommissionTable().setCellEditable(false);
        getFamilyCommissionTable().setAlternateColor(MEUtility.ITEM_FAMILY_COMMISSION_LINE);
        getFamilyCommissionTable().setColumnNames(new String[]{
                    "FAMILLE", "TAUX", "DEBUT", "FIN"
                });
        getFamilyCommissionTable().setPreferredColumnSize(new int[]{
                    80, 70, 75, 75
                });
        getFamilyCommissionTable().setData(getCommissionEmptyTable());
    }

    private Object[][] getCommissionEmptyTable() {
        Object data[][] = new Object[3][4];
        for (int i = 0; i < data.length; i++) {
            if (i == 1) {
                data[i][0] = "AUCUNE";
            } else {
                data[i][0] = null;
            }
            data[i][1] = null;
            data[i][2] = null;
            data[i][3] = null;
        }

        return data;
    }

    private void setFamilyColumn(JTable table, TableColumn familyColumn) {
        JComboBox comboBox = new JComboBox();
        java.util.Collection c = crud.readAll(null, 12);
        if (c != null) {
            ArrayList itemFamilyList = new ArrayList(c);
            Family family;
            for (Iterator it = itemFamilyList.iterator(); it.hasNext(); comboBox.addItem(family.getId())) {
                family = (Family) it.next();
            }

        } else {
            comboBox.addItem("");
        }
        familyColumn.setCellEditor(new DefaultCellEditor(comboBox));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setToolTipText("S\351l\351ctionner une famille");
        familyColumn.setCellRenderer(renderer);
    }

    private void setDateColumn(JTable table, TableColumn dateColumn) {
        DateComboBox comboBox = new DateComboBox();
        dateColumn.setCellEditor(new DefaultCellEditor(comboBox));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setToolTipText("S\351l\351ctionner une date");
        dateColumn.setCellRenderer(renderer);
    }

    private PopupDiscountGUI getPopupDiscount() {
        if (popupDiscount == null) {
            popupDiscount = new PopupDiscountGUI();
        }
        return popupDiscount;
    }

    private void initPopupDiscountListener() {
        getPopupDiscount().getDeleteLine().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionDeleteCommissionLine();
            }
        });
    }

    private void initItemSearch() {
        getItemSearchBox().setList(new String[]{
                    "R\351f\351rence", "D\351signation", "Famille", "Fournisseur"
                });
        getItemSearchBox().setVal("");
        getItemSearchBox().setAdvanceSearch(getItemTable());
        getItemSearchBox().getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionItemSearch();
            }
        });
        getItemSearchBox().getTextField().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionItemSearch();
            }
        });
    }

    private void initItemListTable() {
        itemTable.setTypes(new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
                });
        itemTable.setLastColumnNotEditable(0);
        itemTable.setCellEditable(false);
        itemTable.setAlternateColor(MEUtility.ITEM_LINE);
        itemTable.setColumnNames(new String[]{
                    "REFERENCE", "DESIGNATION", "FAMILLE", "FOURNISSEUR"
                });
        itemTable.setPreferredColumnSize(new int[]{
                    50, 50, 40, 40
                });
        actionItemSearch();
    }

    private TableViewer getItemTable() {
        if (itemTable == null) {
            itemTable = new TableViewer();
        }
        return itemTable;
    }

    private void initCalendar() {
        getCalendarPeriod();
        getPrintPeriod().getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionCalendarPeriod();
            }
        });
    }

    private CalendarPeriod getCalendarPeriod() {
        if (calendarPeriod == null) {
            calendarPeriod = new CalendarPeriod();
            calendarPeriod.setSelectedPeriod(2);
            getPrintPeriod().setLabelLeft(calendarPeriod.getMessage());
            calendarPeriod.getButtonLeft().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriodOK();
                }
            });
            calendarPeriod.getButtonRight().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriodCANCEL();
                }
            });
            calendarPeriod.setLocation(600, 50);
            calendarPeriod.setSize(320, 130);
        }
        return calendarPeriod;
    }

    private void actionExit() {
        setVisible(false);
    }

    private void actionRemove() {
        int reponse = JOptionPane.showConfirmDialog(null, "\nEtes-vous certain de vouloir suprimer ce Commercial ?", "Confirmation", 1, 2, null);
        switch (reponse) {
            case 0: // '\0'
                actionDelete();
            // fall through

            case -1:
            case 1: // '\001'
            case 2: // '\002'
            default:
                return;
        }
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.media-4-u.net");
    }

    private void actionModify() {
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(true);
        getFamilyCommissionTable().setCellEditable(true);
        getItemCommissionTable().setCellEditable(true);
    }

    private void actionNew() {
        initField();
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        create = true;
        getFamilyCommissionTable().setCellEditable(true);
        getItemCommissionTable().setCellEditable(true);
    }

    private void actionPrint(boolean b) {
        SalesPerson salesPerson = (SalesPerson) salesPersonList.get(getSalesPersonComboBox().getSelectedIndex());
        SalesPersonPrint prt = new SalesPersonPrint(salesPerson, getBill(salesPerson.getId().intValue()), getFamilyCommissionTable().getData(), getItemCommissionTable().getData(), true, param);
    }

    private Object[][] getBill(int salesPersonId) {
        SQLList sqlList = new SQLList();
        if (sqlList.search("SELECT id FROM ventes_factures WHERE commerciaux_id=" + salesPersonId + " AND montant_regle = net_a_payer" + " AND solde_le BETWEEN " + getCalendarPeriod().getFromDate() + " AND " + getCalendarPeriod().getToDate() + " ORDER BY solde_le")) {
            return sqlList.getRowsData();
        } else {
            return null;
        }
    }

    private void actionSave() {
        if (create) {
            actionCreate();
        } else {
            actionUpdate();
        }
    }

    private void actionLoad(int index) {
        SalesPerson salesPerson = (SalesPerson) salesPersonList.get(index);
        initField();
        setLastUpdate(salesPerson.getUpdateLastTime());
        setLastUser(salesPerson.getUserId());
        setFirstname(salesPerson.getPrenom());
        setLastname(salesPerson.getNom());
        setAddrLn1(salesPerson.getAddrLn1());
        setAddrLn2(salesPerson.getAddrLn2());
        setZip(salesPerson.getZip());
        setCity(salesPerson.getCity());
        setCountry(salesPerson.getCountry());
        setTel(salesPerson.getTelephone());
        setCel(salesPerson.getPortable());
        setFax(salesPerson.getFax());
        setEmail(salesPerson.getEmail());
        setFamily(salesPerson.getSalesPersonFamily());
        setSector(salesPerson.getSecteur());
        setLevel(salesPerson.getNiveau());
        if (salesPerson.getObjectif() != null) {
            setGoal(salesPerson.getObjectif().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue()).toString());
        }
        if (salesPerson.getResultat() != null) {
            setResult(salesPerson.getResultat().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue()).toString());
        }
        setGoalDate(salesPerson.getObjectifDate());
        setResultDate(salesPerson.getResultatDate());
        if (salesPerson.getTauxVente() != null) {
            setRate1(salesPerson.getTauxVente().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue()).toString());
        }
        if (salesPerson.getTauxTotalVente() != null) {
            setRate2(salesPerson.getTauxTotalVente().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue()).toString());
        }
        setNotes(salesPerson.getCommentaire());
        setTitle("COMMERCIAL (CODE : " + salesPerson.getId() + ")");
        getIconBarPanel().setEnabledModify(write);
        getIconBarPanel().setEnabledPrint(true);
        getMenuPanel().getModify().setEnabled(write);
        getMenuPanel().getPrint().setEnabled(true);
        getItemCommissionTable().setCellEditable(false);
        getFamilyCommissionTable().setCellEditable(false);
        create = false;
        actionLoadItemCommission(salesPerson.getId());
        actionLoadFamilyCommission(salesPerson.getId());
    }

    private void actionUpdate() {
        if (verifyRequirement()) {
            SalesPerson salesPerson = (SalesPerson) salesPersonList.get(getSalesPersonComboBox().getSelectedIndex());
            salesPerson.setUserId(param.getUserId());
            salesPerson.setPrenom(getFirstname());
            salesPerson.setNom(getLastname());
            salesPerson.setAddrLn1(getAddrLn1());
            salesPerson.setAddrLn2(getAddrLn2());
            salesPerson.setZip(getZip());
            salesPerson.setCity(getCity());
            salesPerson.setCountry(getCountry());
            salesPerson.setTelephone(getTel());
            salesPerson.setPortable(getCel());
            salesPerson.setFax(getFax());
            salesPerson.setEmail(getEmail());
            salesPerson.setSalesPersonFamily(getFamily());
            salesPerson.setSecteur(getSector());
            salesPerson.setNiveau(getLevel());
            salesPerson.setObjectif(new BigDecimal(getGoal()));
            salesPerson.setResultat(new BigDecimal(getResult()));
            salesPerson.setObjectifDate(getGoalDate());
            salesPerson.setResultatDate(getResultDate());
            salesPerson.setTauxVente(new BigDecimal(getRate1()));
            salesPerson.setTauxTotalVente(new BigDecimal(getRate2()));
            salesPerson.setCommentaire(getNotes());
            crud.update(salesPerson, 15);
            initField();
            initSalesPersonList();
            initItemCommission();
            initFamilyCommission();
        }
    }

    private void actionCreate() {
        if (verifyRequirement()) {
            Integer pk = (Integer) crud.create(15, null);
            if (pk != null) {
                SalesPerson salesPerson = (SalesPerson) crud.read(pk, 15);
                if (salesPerson != null) {
                    salesPerson.setUserId(param.getUserId());
                    salesPerson.setPrenom(getFirstname());
                    salesPerson.setNom(getLastname());
                    salesPerson.setAddrLn1(getAddrLn1());
                    salesPerson.setAddrLn2(getAddrLn2());
                    salesPerson.setZip(getZip());
                    salesPerson.setCity(getCity());
                    salesPerson.setCountry(getCountry());
                    salesPerson.setTelephone(getTel());
                    salesPerson.setPortable(getCel());
                    salesPerson.setFax(getFax());
                    salesPerson.setEmail(getEmail());
                    salesPerson.setSalesPersonFamily(getFamily());
                    salesPerson.setSecteur(getSector());
                    salesPerson.setNiveau(getLevel());
                    salesPerson.setObjectif(new BigDecimal(getGoal()));
                    salesPerson.setResultat(new BigDecimal(getResult()));
                    salesPerson.setObjectifDate(getGoalDate());
                    salesPerson.setResultatDate(getResultDate());
                    salesPerson.setTauxVente(new BigDecimal(getRate1()));
                    salesPerson.setTauxTotalVente(new BigDecimal(getRate2()));
                    salesPerson.setCommentaire(getNotes());
                    crud.update(salesPerson, 15);
                    initField();
                    initSalesPersonList();
                    initItemCommission();
                    initFamilyCommission();
                }
            } else {
                JOptionPane.showMessageDialog(null, "Cr\351ation refus\351e !");
            }
        }
    }

    private void actionDelete() {
        SalesPerson salesPerson = (SalesPerson) salesPersonList.get(getSalesPersonComboBox().getSelectedIndex());
        crud.delete(salesPerson.getId(), salesPerson.getUpdateLastTime(), 15);
        initField();
        initSalesPersonList();
    }

    private boolean verifyRequirement() {
        if (getFirstname() != null && getFirstname().length() > 50) {
            JOptionPane.showMessageDialog(null, "Pr\351nom trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getLastname() != null && getLastname().length() > 50) {
            JOptionPane.showMessageDialog(null, "Nom trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getAddrLn1() != null && getAddrLn1().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse ligne 1 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getAddrLn2() != null && getAddrLn2().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse ligne 2 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getZip() != null && getZip().length() > 20) {
            JOptionPane.showMessageDialog(null, "Code postal trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getCity() != null && getCity().length() > 50) {
            JOptionPane.showMessageDialog(null, "Ville trop longue (maxi. 50 caract\350res) !");
            return false;
        }
        if (getCountry() != null && getCountry().length() > 50) {
            JOptionPane.showMessageDialog(null, "Pays trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getTel() != null && getTel().length() > 20) {
            JOptionPane.showMessageDialog(null, "T\351l trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getFax() != null && getFax().length() > 20) {
            JOptionPane.showMessageDialog(null, "Fax trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getCel() != null && getCel().length() > 20) {
            JOptionPane.showMessageDialog(null, "Portable trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getEmail() != null && getEmail().length() > 100) {
            JOptionPane.showMessageDialog(null, "Email trop long (maxi. 100 caract\350res) !");
            return false;
        }
        if (getSector() != null && getSector().length() > 50) {
            JOptionPane.showMessageDialog(null, "Secteur trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getLevel() != null && getLevel().length() > 50) {
            JOptionPane.showMessageDialog(null, "Niveau trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getNotes() != null && getNotes().length() > 250) {
            JOptionPane.showMessageDialog(null, "Commentaire trop long (maxi. 250 caract\350res) !");
            return false;
        }
        try {
            new BigDecimal(getGoal());
        } catch (NumberFormatException nfe) {
            setGoal("0.00");
            JOptionPane.showMessageDialog(null, "Objectif refus\351 (nombre d\351cimal uniquement) !");
        }
        try {
            new BigDecimal(getResult());
        } catch (NumberFormatException nfe) {
            setResult("0.00");
            JOptionPane.showMessageDialog(null, "R\351sultat refus\351 (nombre d\351cimal uniquement) !");
        }
        try {
            new BigDecimal(getRate1());
        } catch (NumberFormatException nfe) {
            setRate1("0.00");
            JOptionPane.showMessageDialog(null, "Taux 1 refus\351 (nombre d\351cimal uniquement) !");
        }
        try {
            new BigDecimal(getRate2());
        } catch (NumberFormatException nfe) {
            setRate2("0.00");
            JOptionPane.showMessageDialog(null, "Taux 2 refus\351 (nombre d\351cimal uniquement) !");
        }
        return true;
    }

    private void actionLoadItemCommission(Integer salesPersonId) {
        java.util.Collection c = crud.readAll(salesPersonId, 16);
        if (c != null) {
            itemCommissionList = new ArrayList(c);
            Object data[][] = new Object[itemCommissionList.size() + 5][8];
            Iterator it = itemCommissionList.iterator();
            for (int i = 0; it.hasNext(); i++) {
                Commission comm = (Commission) it.next();
                data[i][0] = comm.getArticleId();
                data[i][1] = comm.getT().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue());
                data[i][2] = comm.getDebut();
                data[i][3] = comm.getFin();
            }

            for (int i = itemCommissionList.size(); i < itemCommissionList.size() + 5; i++) {
                data[i][0] = null;
                data[i][1] = null;
                data[i][2] = null;
                data[i][3] = null;
            }

            getItemCommissionTable().setData(data);
        } else {
            itemCommissionList = null;
            getItemCommissionTable().setData(getCommissionEmptyTable());
        }
        getItemCommissionTable().getTable().addMouseListener(new MouseClickItemCommissionList());
        setDateColumn(getItemCommissionTable().getTable(), getItemCommissionTable().getTable().getColumnModel().getColumn(2));
        setDateColumn(getItemCommissionTable().getTable(), getItemCommissionTable().getTable().getColumnModel().getColumn(3));
        getItemCommissionTable().getTableModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                if (updateRowsTable) {
                    actionUpdateItemCommissionRow(e.getFirstRow(), e.getColumn());
                }
            }
        });
    }

    private void actionLoadFamilyCommission(Integer salesPersonId) {
        java.util.Collection c = crud.readAll(salesPersonId, 50);
        if (c != null) {
            familyCommissionList = new ArrayList(c);
            Object data[][] = new Object[familyCommissionList.size() + 5][8];
            Iterator it = familyCommissionList.iterator();
            for (int i = 0; it.hasNext(); i++) {
                Commission comm = (Commission) it.next();
                data[i][0] = comm.getArticleId();
                data[i][1] = comm.getT().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue());
                data[i][2] = comm.getDebut();
                data[i][3] = comm.getFin();
            }

            for (int i = familyCommissionList.size(); i < familyCommissionList.size() + 5; i++) {
                data[i][0] = null;
                data[i][1] = null;
                data[i][2] = null;
                data[i][3] = null;
            }

            getFamilyCommissionTable().setData(data);
        } else {
            familyCommissionList = null;
            getFamilyCommissionTable().setData(getCommissionEmptyTable());
        }
        setFamilyColumn(getFamilyCommissionTable().getTable(), getFamilyCommissionTable().getTable().getColumnModel().getColumn(0));
        setDateColumn(getFamilyCommissionTable().getTable(), getFamilyCommissionTable().getTable().getColumnModel().getColumn(2));
        setDateColumn(getFamilyCommissionTable().getTable(), getFamilyCommissionTable().getTable().getColumnModel().getColumn(3));
        getFamilyCommissionTable().getTable().addMouseListener(new MouseClickFamilyCommissionList());
        getFamilyCommissionTable().getTableModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                if (updateRowsTable) {
                    actionUpdateFamilyCommissionRow(e.getFirstRow());
                }
            }
        });
    }

    private void actionUpdateItemCommissionRow(int row, int col) {
        SalesPerson salesPerson = (SalesPerson) salesPersonList.get(getSalesPersonComboBox().getSelectedIndex());
        if (itemCommissionList == null || row >= itemCommissionList.size()) {
            Integer pk = (Integer) crud.create(16, null);
            if (pk != null) {
                Object data[][] = getItemCommissionTable().getData();
                Commission commission = (Commission) crud.read(pk, 16);
                commission.setCommerciauxId(salesPerson.getId());
                commission.setArticleId((String) data[row][0]);
                if (data[row][1] == null) {
                    commission.setT(new BigDecimal("0.00"));
                } else {
                    commission.setT((BigDecimal) data[row][1]);
                }
                commission.setDebut((String) data[row][2]);
                commission.setFin((String) data[row][3]);
                commission.setUpdateUserId(param.getUserId());
                crud.update(commission, 16);
            }
        } else {
            Object data[][] = getItemCommissionTable().getData();
            Commission commission = (Commission) itemCommissionList.get(row);
            commission.setArticleId((String) data[row][0]);
            if (data[row][1] == null) {
                commission.setT(new BigDecimal("0.00"));
            } else {
                commission.setT((BigDecimal) data[row][1]);
            }
            commission.setDebut((String) data[row][2]);
            commission.setFin((String) data[row][3]);
            commission.setUpdateUserId(param.getUserId());
            crud.update(commission, 16);
        }
        actionLoadItemCommission(salesPerson.getId());
    }

    private void actionUpdateFamilyCommissionRow(int row) {
        SalesPerson salesPerson = (SalesPerson) salesPersonList.get(getSalesPersonComboBox().getSelectedIndex());
        if (familyCommissionList == null || row >= familyCommissionList.size()) {
            Integer pk = (Integer) crud.create(50, null);
            if (pk != null) {
                Object data[][] = getFamilyCommissionTable().getData();
                Commission commission = (Commission) crud.read(pk, 50);
                commission.setCommerciauxId(salesPerson.getId());
                commission.setArticleId((String) data[row][0]);
                if (data[row][1] == null) {
                    commission.setT(new BigDecimal("0.00"));
                } else {
                    commission.setT((BigDecimal) data[row][1]);
                }
                commission.setDebut((String) data[row][2]);
                commission.setFin((String) data[row][3]);
                commission.setUpdateUserId(param.getUserId());
                crud.update(commission, 50);
            }
        } else {
            Object data[][] = getFamilyCommissionTable().getData();
            Commission commission = (Commission) familyCommissionList.get(row);
            commission.setArticleId((String) data[row][0]);
            if (data[row][1] == null) {
                commission.setT(new BigDecimal("0.00"));
            } else {
                commission.setT((BigDecimal) data[row][1]);
            }
            commission.setDebut((String) data[row][2]);
            commission.setFin((String) data[row][3]);
            commission.setUpdateUserId(param.getUserId());
            crud.update(commission, 50);
        }
        actionLoadFamilyCommission(salesPerson.getId());
    }

    private void actionDeleteCommissionLine() {
        SalesPerson salesPerson = (SalesPerson) salesPersonList.get(getSalesPersonComboBox().getSelectedIndex());
        if (getSelectedCommissionPanel() == 0) {
            Commission commission = (Commission) itemCommissionList.get(getItemCommissionTable().getTable().getSelectedRow());
            crud.delete(commission.getId(), commission.getUpdateTime(), 16);
            actionLoadItemCommission(salesPerson.getId());
        } else if (getSelectedCommissionPanel() != -1) {
            Commission commission = (Commission) familyCommissionList.get(getFamilyCommissionTable().getTable().getSelectedRow());
            crud.delete(commission.getId(), commission.getUpdateTime(), 50);
            actionLoadFamilyCommission(salesPerson.getId());
        }
    }

    private void actionItemSearch() {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT ref_code_barre, designation, familles_articles_id, fournisseurs_id FROM articles");
        switch (getItemSearchBox().getSelectedIndex()) {
            case 0: // '\0'
                if (getItemSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY ref_code_barre");
                } else {
                    sql.append(" WHERE ref_code_barre LIKE '");
                    sql.append(getItemSearchBox().getVal());
                    sql.append("%' ORDER BY ref_code_barre");
                }
                break;

            case 1: // '\001'
                if (getItemSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY designation");
                } else {
                    sql.append(" WHERE designation LIKE '");
                    sql.append(getItemSearchBox().getVal());
                    sql.append("%' ORDER BY designation");
                }
                break;

            case 2: // '\002'
                if (getItemSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY familles_articles_id");
                } else {
                    sql.append(" WHERE familles_articles_id LIKE '");
                    sql.append(getItemSearchBox().getVal());
                    sql.append("%' ORDER BY familles_articles_id");
                }
                break;

            case 3: // '\003'
                if (getItemSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY fournisseurs_id");
                } else {
                    sql.append(" WHERE fournisseurs_id LIKE '");
                    sql.append(getItemSearchBox().getVal());
                    sql.append("%' ORDER BY fournisseurs_id");
                }
                break;

            default:
                if (getItemSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY ref_code_barre");
                } else {
                    sql.append(" WHERE ref_code_barre LIKE '");
                    sql.append(getItemSearchBox().getVal());
                    sql.append("%' ORDER BY ref_code_barre");
                }
                break;
        }
        Object data[][] = itemCrud.getDataList(sql.toString());
        if (data != null) {
            itemTable.setData(data);
            itemTable.getTable().addMouseListener(new MouseClickItemList());
        } else {
            itemTable.setData(getEmptyItemTable());
        }
    }

    private Object[][] getEmptyItemTable() {
        Object data[][] = new Object[3][4];
        for (int i = 0; i < data.length; i++) {
            data[i][0] = null;
            if (i == 1) {
                data[i][1] = "AUCUN";
                data[i][2] = "ARTICLE";
            } else {
                data[i][1] = null;
                data[i][2] = null;
            }
            data[i][3] = null;
        }

        return data;
    }

    private void actionCalendarPeriod() {
        getCalendarPeriod().setVisible(true);
        getCalendarPeriod().toFront();
        param.getDesktop().add(getCalendarPeriod(), JLayeredPane.DEFAULT_LAYER);
        try {
            getCalendarPeriod().setSelected(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    private void actionCalendarPeriodOK() {
        getPrintPeriod().setLabelLeft(getCalendarPeriod().getMessage());
        actionCalendarPeriodCANCEL();
    }

    private void actionCalendarPeriodCANCEL() {
        getCalendarPeriod().setVisible(false);
        param.getDesktop().remove(getCalendarPeriod());
    }
    private ObjectCRUD crud;
    private Parameter param;
    private ArrayList salesPersonList;
    private ArrayList itemCommissionList;
    private ArrayList familyCommissionList;
    private boolean create;
    private boolean updateRowsTable;
    private boolean write;
    private PopupDiscountGUI popupDiscount;
    private TableViewer itemTable;
    private ItemCRUD itemCrud;
    private CalendarPeriod calendarPeriod;
}
